<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号" prop="username">
        <el-input
            v-model="queryParams.username"
            placeholder="请输入账号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
            v-model="queryParams.nickName"
            placeholder="请输入昵称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender" style="width: 200px">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option
              v-for="dict in user_sex_gender_options"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
            v-model="queryParams.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="管理员" prop="isAdmin" style="width: 250px">
        <el-select v-model="queryParams.isAdmin" placeholder="请选择是否是管理员" clearable>
          <el-option
              v-for="dict in is_admin_options"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户编号" align="center" prop="id" />
      <el-table-column label="账号" align="center" prop="username" />
<!--      <el-table-column label="密码" align="center" prop="password" />-->
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="头像" align="center" prop="header" >
        <template #default="scope">
          <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.header"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              :preview-src-list="[scope.row.header]"
              :preview-teleported="true"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <span>{{scope.row.gender===0?'女':'男'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="当前身份" align="center" prop="isAdmin">
        <template #default="scope">
          <span v-if="scope.row.isAdmin===0">管理员</span>
          <span v-else-if="scope.row.isAdmin===1">车主</span>
          <span v-else>货主</span>
        </template>
      </el-table-column>
      <el-table-column label="上次登陆时间" align="center" prop="lastLoginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-show="total>0"
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @current-change="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body :lock-scroll="false">
      <el-form ref="userRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="头像" prop="header">
          <el-input v-model="form.header" placeholder="请输入头像" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option
                v-for="dict in user_sex_gender_options"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="是否是管理员" prop="isAdmin">
          <el-select v-model="form.isAdmin" placeholder="请选择是否是管理员">
            <el-option
                v-for="dict in is_admin_options"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="逻辑删除列" prop="delFlag">
          <el-select v-model="form.delFlag" placeholder="请选择逻辑删除状态">
            <el-option
                v-for="dict in del_flag_options"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">用户车辆明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddUserCarDetails">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteUserCarDetails">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="carList" :row-class-name="rowUserCarDetailsIndex" @selection-change="handleUserCarDetailsSelectionChange" ref="userCarDetails">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="80"/>
          <el-table-column label="车牌号" align="center" prop="card" width="100"/>
          <el-table-column label="车型" align="center" prop="types" width="100"/>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  绑定车辆  -->
    <el-dialog title="绑定车辆" v-model="carListOpen" width="500px" :before-close="addCarCancel" append-to-body :lock-scroll="false">
      <el-select v-model="currentAddCarCard" placeholder="请选择需要关联的车辆">
        <el-option
            v-for="dict in allCarList"
            :key="dict.card"
            :label="dict.card"
            :value="dict.card"
        ></el-option>
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addCarSubmit">确 定</el-button>
          <el-button @click="addCarCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/user";
import {getCurrentInstance, reactive, ref,toRefs } from "vue";
import {parseTime} from "@/utils/common";
import {ElMessage, ElMessageBox} from "element-plus";
import request from "@/utils/request";

const { proxy } = getCurrentInstance();
const userList = ref([]);
const carList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedUserCarDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const allCarList = ref([])
const carListOpen = ref(false)
const currentAddCarCard = ref("")
const user_sex_gender_options= [
  {
    value: 1,
    label: '男',
  },
  {
    value: 0,
    label: '女',
  }
]

const is_admin_options=[
  {
    value: 1,
    label: '普通用户',
  },
  {
    value: 0,
    label: '管理员',
  }
]

const del_flag_options=[
  {
    value: 1,
    label: '已删除',
  },
  {
    value: 0,
    label: '未删除',
  }
]

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    password: null,
    nickName: null,
    header: null,
    gender: null,
    email: null,
    isAdmin: null,
    lastLoginTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then(response => {
    if(response.code===200){
      userList.value = response.data.records;
      total.value = response.data.total;
    }
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    username: null,
    password: null,
    nickName: null,
    header: null,
    gender: null,
    email: null,
    isAdmin: null,
    updateBy: null,
    updateTime: null,
    lastLoginTime: null,
    delFlag: null
  };
  carList.value = [];
  proxy.resetForm("userRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUser(_id).then(response => {
    form.value = response.data;
    carList.value = response.data.carList;
    open.value = true;
    title.value = "修改用户";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      form.value.carList = carList.value;
      if (form.value.id != null) {
        updateUser(form.value).then(response => {
          ElMessage.success('修改成功')
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then(response => {
          if(response.code===200){
            ElMessage.success("新增成功");
          }
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除用户编号为"' + _ids + '"的数据项？').then(function() {
    return delUser(_ids);
  }).then(() => {
    getList();
    ElMessage.success('删除成功')
  }).catch(() => {});
}

/** 用户车辆明细序号 */
function rowUserCarDetailsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 用户车辆明细添加按钮操作 */
function handleAddUserCarDetails() {
  // 清空上一次残留的用户添加信息
  allCarList.value=[]
  currentAddCarCard.value=null
  request.get('/car/listAll').then((res) => {
    if (res.code === 200) {
      let allCar=res.data
      // 过滤掉已经添加过的用户
      let result = allCar.reduce((pre, cur) => {
        if (!carList.value.some(item => item.card === cur.card)) {
          pre.push(cur)
        }
        return pre
      }, [])
      result.forEach(function (item) {
        allCarList.value.push(item);
      })
    }
  }).catch((err) => {
    console.log("err:", err);
  })
  carListOpen.value = true
}

/** 用户车辆明细删除按钮操作 */
function handleDeleteUserCarDetails() {
  if (checkedUserCarDetails.value.length == 0) {
    ElMessage.error("请先选择要删除的用户车辆明细数据");
  } else {
    const userCarDetailss = carList.value;
    const checkedUserCarDetailss = checkedUserCarDetails.value;
    carList.value = userCarDetailss.filter(function(item) {
      return checkedUserCarDetailss.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleUserCarDetailsSelectionChange(selection) {
  checkedUserCarDetails.value = selection.map(item => item.index)
}

/** 确认添加用户 */
function addCarSubmit(){
  // 关闭对话框
  carListOpen.value=false
  // 当前选择的用户信息
  let chooseCar=allCarList.value.filter(item=>item.card===currentAddCarCard.value)[0]
  carList.value.push(chooseCar)
}

/** 取消添加用户 */
function addCarCancel(){
  carListOpen.value=false
}

getList();
</script>